package com.icehand.json.utils;

import com.alibaba.fastjson.JSONObject;
import okhttp3.*;

import java.io.IOException;
import java.util.concurrent.TimeUnit;

/**
 * @author zhoujunmei
 * @date 2019-08-05
 */
public class OkHttpUtil {
    private final static OkHttpClient okHttpClient = new OkHttpClient.Builder()
            .connectionPool(new ConnectionPool(20,5, TimeUnit.MINUTES))
            .readTimeout(20,TimeUnit.MINUTES)
            .connectTimeout(20,TimeUnit.SECONDS).build();

    public static String post(String url, Object object){
        RequestBody requestBody = RequestBody.create(JSONObject.toJSONString(object),MediaType.parse("application/json; charset=utf-8"));
        System.out.println(JSONObject.toJSONString(object));
        Request request = new Request.Builder()
                .url(url)
                .post(requestBody)
                .build();
        try {
            Response response = okHttpClient.newCall(request).execute();
            if(response.isSuccessful() && null != response.body()){
                return response.body().string();
            }
        } catch (IOException e) {
            e.printStackTrace();
            return null;
        }
        return null;
    }
}
